package com.wql.test.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wql.test.constant.Constant;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * <strong>
 * Desc:后置过滤器
 * </strong>
 * <p>Author: WeiQiLong<p>
 * Create Time:2019/8/18 14:25<p>
 */
@Component
public class PostRequestFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * Desc: 获取上个过滤器返回的“isOk”，如果是flase，就不执行此过滤器了(不执行此过滤器的run方法)
     * Author: WeiQiLong
     * Create Time:2019/8/18 14:46
     * @param
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean isOk = (boolean)currentContext.get("isOk");
        return isOk;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("post请求过滤器...");
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = context.getResponse();

        int statusCode = context.getResponseStatusCode();
        if(HttpServletResponse.SC_OK != statusCode){
            throw new RuntimeException("执行错误");
        }
        //此处，如果dataStream是异常信息，打印出来的是乱码，不知道原因~!
        InputStream dataStream = context.getResponseDataStream();
        try {
            String string = StreamUtils.copyToString(dataStream, Charset.forName(Constant.ENCODING));
            context.setResponse(response);
            context.setResponseBody("返回内容:"+string);
            System.out.println("post请求过滤器:"+response.getCharacterEncoding()+","+response.getContentType());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("执行错误:"+e.getMessage());
        }
        return null;
    }
}
